import java.util.Arrays;

public class TestHeap {
    public int[] elem;
    public int useSize;

    public TestHeap() {
        this.elem = new int[10];
    }

    public void initElem(int[] arry) {
        for (int i = 0; i < arry.length; i++) {
            this.elem[i] = arry[i];
            useSize++;
        }
    }

    public void createHeap() {
        for (int parent = (this.useSize - 1 - 1) / 2; parent >= 0; parent--) {
            siftDown(parent, this.useSize);

        }
    }

    //parent 每颗子树调整的时候的起始位置
    //useSize 每颗子树调整的时候的结束
    private void siftDown(int parent, int useSize) {
        int child = 2 * parent + 1;
        while (child < useSize) {
            //找到左右孩子的最大值
            if (child+1<useSize&&elem[child]<elem[child+1]){
                child++;
            }
            if(elem[child]>elem[parent]){
                int tmp=elem[child];
                elem[child]=elem[parent];
                elem[parent]=tmp;
                parent=child;
                child=2*parent+1;
            }else{
                break;
            }
        }
    }

    public void push(int val){
        if(isFull()){
            elem= Arrays.copyOf(elem,elem.length*2);
        }
        elem[useSize]=val;

        siftUp(useSize);
        useSize++;
    }

    private void siftUp(int child) {
        int parent=(child-1)/2;
        while(parent>=0){
            if(elem[parent]<elem[child]){
                int tmp=elem[parent];
                elem[parent]=elem[child];
                elem[child]=tmp;
                child=parent;
                parent=(child-1)/2;
            }else {
                break;
            }
        }
    }

    private boolean isFull() {
        return useSize==elem.length;
    }

    public int poll(){
        int val=elem[0];
        int tmp=elem[0];
        elem[0]=elem[useSize-1];
        elem[useSize-1]=tmp;

        siftDown(0,useSize-1);
        useSize--;
        return val;
    }
}
